package com.zpc.myvideoserver.common.security.handler;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.zpc.myvideoserver.common.security.pojo.AccountUser;
import com.zpc.myvideoserver.common.security.util.JwtUtil;
import com.zpc.myvideoserver.common.util.ResponseJson;
import com.zpc.myvideoserver.entity.LoginUser;
import com.zpc.myvideoserver.entity.User;
import com.zpc.myvideoserver.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName : LoginSuccessHandler  //类名
 * @Description : 登录成功处理类  //描述
 * @Author : zpc20 //作者
 * @Date: 2023/11/1  22:46
 */

@Component//注入容器
// 实现验证成功处理类
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired //注入jwt工具类
    JwtUtil jwtUtil;

    @Autowired
    UserService userService;

    /**
     * @Name: onAuthenticationSuccess
     * @Params : [request, response, authentication]:[javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication]
     * @Description : 验证成功处理方法
     * @Author : zpc20
     * @Date : 2023/11/1 23:03
     * @Return void
     * @Throws
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // @Description : 获取验证成功用户信息 zpc20 2023/11/4 1:05
        AccountUser accountUser = (AccountUser) authentication.getPrincipal();
        // @Description : 组装token用于返回前端 zpc20 2023/11/4 1:09
        String token = jwtUtil.createToken(accountUser);
        token = jwtUtil.getPrefix()+token;
        // @Description : 从数据库获取用户相关信息用于前端用户信息展示 zpc20 2023/11/4 1:12
        User user = userService.getById(accountUser.getUserId());
        ResponseJson<Object> responseJson = new ResponseJson<>();
        responseJson.setCode(200);
        responseJson.setMsg("登录成功!");
        Map<String,Object> res = new HashMap<>();
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(user,loginUser);
        res.put("LoginUser", loginUser);
        res.put("token",token);
        responseJson.setObj(res);
        ResponseJson.SecurityResponse(response,responseJson);

    }
}
